<?php declare(strict_types=1);

namespace think\msg\platform\feishu;

use think\msg\msg\Msg;
use think\msg\msg\RichTextMsg;
use think\msg\msg\TextMsg;
use think\msg\MsgException;
use think\msg\platform\feishu\convertor\MsgConvertor;
use think\msg\platform\feishu\dto\RichTextMsgDto;
use think\msg\platform\feishu\dto\TextMsgDto;
use think\msg\platform\MsgPlatform;

class FeishuBot extends MsgPlatform
{
    public const NAME = 'feishu';

    /**
     * @throws MsgException
     */
    protected function send(Msg $msg): void
    {
        if ($msg instanceof TextMsg) {
            $this->sendText(MsgConvertor::toTextMsgDto($msg));
        } elseif ($msg instanceof RichTextMsg) {
            $this->sendRichText(MsgConvertor::toRichTextMsgDto($msg));
        }
    }

    /**
     * 飞书实现发送文本消息
     * @param TextMsgDto $textMsgDto
     * @return void
     * @throws MsgException
     */
    private function sendText(TextMsgDto $textMsgDto)
    {
        $data = $textMsgDto->toArray();
        $this->httpPost($this->config['webhook'], $data);
    }

    /**
     * @throws MsgException
     */
    private function sendRichText(RichTextMsgDto $toRichTextMsgDto)
    {
        $data = $toRichTextMsgDto->toArray();
        $this->httpPost($this->config['webhook'], $data);
    }

    /**
     * 飞书接口请求正常响应：
     * {"StatusCode":0,"StatusMessage":"success","code":0,"data":{},"msg":"success"}
     * 出错响应：
     * {"code":10208,"data":{},"msg":"msg type text2 not support"}
     * @throws MsgException
     */
    private function httpPost($webhook, array $data)
    {
        $this->context->setRequestParams($webhook, $data);
        // todo shali [2025/6/9] 引入 http client 完成消息发送
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $webhook);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        // todo shali [2025/6/9] 临时禁用证书验证，后续优化
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        $this->context->setResponseBody($result);
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new MsgException($error);
        }
        curl_close($ch);
        return $result;
    }
}